from iamadb import iamadb
from datetime import datetime

baselink = "http://www.reddit.com"
csslink = "<link rel='stylesheet' type='text/css' href='iama.css' />"
with iamadb("iama.sqlite") as db:
    threads = db.getAllThreads()
    index = open('index.html', 'w')
    index.write("<!DOCTYPE html><html><head><meta charset='UTF-8' />" + csslink + "<script src='sorttable.js'></script><title>IAMA list</title></head><body><table class='sortable' id='iamatable'><tr><th>Author</th><th>Last update</th><th>Title</th></tr>")
    for thread in threads:
        conversations = db.getConversations(thread.id)
        filename = "".join([c for c in thread.title if c.isalpha() or c.isdigit() or c==' ']).rstrip().lower().replace(' ', '_')[:200] + ".html"
        f = open(filename, 'w')
        f.write("<!DOCTYPE html><html><head><meta charset='UTF-8' /><title>{0}</title>{1}</head><body><a class='title' href='{2}' target='_blank'>{0}</a><div id='intro'><pre>{3}</pre></div>".format(thread.title, csslink, baselink + thread.url, thread.body))
        for c in conversations:
            f.write("""<div class='conversation'>
        <div class='question'><pre class='question'>{0}</pre> ({1})<div class='link'><a href='{2}' target='_blank'>(link)</a></div></div>
        <div class='response'><pre>{3}</pre> ({4})<div class='link'><a href='{5}' target='_blank'>(link)</a></div></div>
        </div>""".format(c.q_body.replace('\n\n', '\n'), c.q_author, baselink + thread.url + c.q_id[3:], c.a_body.replace('\n\n', '\n'), c.a_author, baselink + thread.url + c.a_id[3:]))
        f.write("</body></html>")
        f.close()
        index.write("<tr><td>{0}</td><td>{1}</td><td><a href='{2}'>{3}</a></td></tr>".format(thread.author, datetime.fromtimestamp(thread.last_update).strftime('%Y-%m-%d'), filename, thread.title))
        print(filename + " generated.")
    index.write('</table></body></html>')
    index.close()
    print('done.')
